import { defineStore } from 'pinia'
import { ref } from 'vue'
import { clearAllRouteCaches, initializeDynamicRoutes } from '@/router/dynamic'
import router from '@/router'
import type { User, LoginForm, LoginResponse } from '../types'
import { authService } from '@/api/auth'


export const useAuthStore = defineStore('auth', () => {
  // 用户token
  const token = ref<string>(localStorage.getItem('token') || '')
  
  // 用户信息
  const userInfo = ref<LoginResponse | null>(null)
  
  // 是否已登录
  const isLoggedIn = ref<boolean>(!!token.value)

  // 清理路由缓存的函数
  const clearRouteCache = () => {
    const routeCacheKeys = [
      'user_permissions_cache',
      'dynamic_routes_cache', 
      'routes_initialized'
    ]
    routeCacheKeys.forEach(key => {
      localStorage.removeItem(key)
    })
  }

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
    isLoggedIn.value = true
  }

  // 设置用户信息
  const setUserInfo = (info: LoginResponse) => {
    userInfo.value = info
  }

  // 登录 - 接收登录响应数据
  const login = async (loginData: LoginResponse) => {
    setToken(loginData.token)
    setUserInfo(loginData)
    
    try {
      const permissions = await authService.getCurrentUserPermissions()

      // 缓存用户权限到localStorage
      if (permissions && permissions.length > 0) {
        const cacheData = {
          data: permissions,
          timestamp: Date.now(),
          expiry: 30 * 60 * 1000, // 30分钟过期
        }

        localStorage.setItem('user_permissions_cache', JSON.stringify(cacheData))
        
        await initializeDynamicRoutes(router)

        // 跳转到首页
      router.push('/dashboard')
      }
    } catch (error) {
      console.error('获取权限或初始化路由失败:', error)
    }
  }

  // 登出
  const logout = async () => {
    try {
      // 清理本地状态
      token.value = ''
      userInfo.value = null
      isLoggedIn.value = false
      localStorage.removeItem('token')
      
      // 清理路由相关缓存
      clearAllRouteCaches()
      
    } catch (error) {
      throw error
    }
  }

  // 清除认证数据
  const clearAuth = () => {
    logout()
  }

  const checkAuth = () => {
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      token.value = savedToken
      return true
    }
    return false
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    setToken,
    setUserInfo,
    login,
    logout,
    clearAuth,
    checkAuth
  }
}) 